{% extends "base.html" %}
{% load static %}

{% block title %}订阅数据仪表板{% endblock %}

{% block content %}
    <div class="container mt-4">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>订阅数据仪表板</h2>
            <div class="d-flex align-items-center">
                <div class="form-check form-switch me-3">
                    <input class="form-check-input" type="checkbox" id="voiceAlertSwitch" checked>
                    <label class="form-check-label" for="voiceAlertSwitch">
                        <i class="bi bi-volume-up"></i> 语音提醒
                    </label>
                </div>
                <button type="button" class="btn btn-outline-primary btn-sm" data-bs-toggle="modal"
                        data-bs-target="#voiceSettingsModal">
                    <i class="bi bi-gear"></i> 语音设置
                </button>
            </div>
        </div>

        <div class="dashboard-container">
            <div class="row">
                <!-- OPC UA订阅 -->
                <div class="col-md-12">
                    <div class="card mb-4">
                        <div class="card-header">
                            <h3 class="card-title h5 mb-0">
                                <i class="bi bi-hdd-network"></i> OPC UA订阅
                            </h3>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                    <tr>
                                        <th style="width: 15%">数据源</th>
                                        <th style="width: 25%">监控项</th>
                                        <th>报警条件</th>
                                        <th>阀值</th>
                                        <th>状态</th>
                                        <th>当前值</th>
                                        <th>单位</th>
                                        <th>更新时间</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    {% for subscription in opcua_subscriptions %}
                                        <tr id="opcua-{{ subscription.id }}">
                                            <td>{{ subscription.data_source.name }}</td>
                                            <td>{{ subscription.name }}</td>
                                            <td>{{ subscription.get_condition_display }}</td>
                                            {% if subscription.condition == 'range' %}
                                                <td>{{ subscription.threshold_value }} ~ {{ subscription.threshold_max }}</td>
                                            {% else %}
                                                <td>{{ subscription.threshold_value }}</td>
                                            {% endif %}
                                            <td>
                                                <span class="badge bg-secondary status">未连接</span>
                                            </td>
                                            <td class="value">--</td>
                                            <td>{{ subscription.unit }}</td>
                                            <td class="timestamp">--</td>
                                        </tr>
                                    {% empty %}
                                        <tr>
                                            <td colspan="5" class="text-center text-muted">暂无订阅</td>
                                        </tr>
                                    {% endfor %}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- MQTT订阅 -->
                <div class="col-md-12">
                    <div class="card mb-4">
                        <div class="card-header">
                            <h3 class="card-title h5 mb-0">
                                <i class="bi bi-broadcast"></i> MQTT订阅
                            </h3>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                    <tr>
                                        <th style="width: 10%">数据源</th>
                                        <th style="width: 10%">主题</th>
                                        <th style="width: 20%">监控项</th>
                                        <th style="width: 10%">报警条件</th>
                                        <th style="width: 10%">阈值</th>
                                        <th style="width: 5%">状态</th>
                                        <th style="width: 10%">当前值</th>
                                        <th style="width: 10%">单位</th>
                                        <th style="width: 15%">更新时间</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    {% for subscription in mqtt_subscriptions %}
                                        <tr id="mqtt-subscription-{{ subscription.id }}">
                                            <td>{{ subscription.data_source.name }}</td>
                                            <td>{{ subscription.topic }}</td>
                                            <td colspan="7">
                                                <div class="table-responsive">
                                                    <table class="table table-sm mb-0">
                                                        <tbody>
                                                        {% for item in subscription.mqttsubscriptionitem_set.all %}
                                                            <tr id="mqtt-item-{{ item.id }}"
                                                                data-values-id="{{ item.values_id }}">
                                                                <td style="width: 25%">{{ item.name }}</td>
                                                                <td style="width: 13%">{{ item.get_condition_display }}</td>
                                                                {% if item.condition == 'range' %}
                                                                    <td style="width: 12%">{{ item.threshold_value }} ~ {{ item.threshold_max }}</td>
                                                                {% else %}
                                                                    <td style="width: 12%">{{ item.threshold_value }}</td>
                                                                {% endif %}
                                                                <td style="width: 7%">
                                                                    <span class="badge bg-secondary status">未连接</span>
                                                                </td>
                                                                <td class="value" style="width: 12%">--</td>
                                                                <td style="width: 10%">{{ item.unit }}</td>
                                                                <td class="timestamp">--</td>
                                                            </tr>
                                                        {% endfor %}
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </td>
                                        </tr>
                                    {% empty %}
                                        <tr>
                                            <td colspan="9" class="text-center text-muted">暂无订阅</td>
                                        </tr>
                                    {% endfor %}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>

    <!-- 语音设置模态框 -->
    <div class="modal fade" id="voiceSettingsModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">语音提醒设置</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">音量</label>
                        <input type="range" class="form-range" id="voiceVolume" min="0" max="1" step="0.1" value="1">
                        <div class="form-text text-end"><span id="volumeValue">100</span>%</div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">语速</label>
                        <input type="range" class="form-range" id="voiceRate" min="0.5" max="2" step="0.1" value="1">
                        <div class="form-text text-end"><span id="rateValue">100</span>%</div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">音高</label>
                        <input type="range" class="form-range" id="voicePitch" min="0.5" max="2" step="0.1" value="1">
                        <div class="form-text text-end"><span id="pitchValue">100</span>%</div>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="voiceRepeat" checked>
                        <label class="form-check-label">重要报警重复播报</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" onclick="testVoiceSettings()">
                        <i class="bi bi-play"></i> 测试语音
                    </button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block extra_js %}
    <script>
        function resetForm() {
            // 清空所有表单字段
            const form = document.getElementById('search-form');
            const inputs = form.querySelectorAll('input, select');
            inputs.forEach(input => {
                if (input.type === 'checkbox') {
                    input.checked = false;
                } else {
                    input.value = '';
                }
            });

            // 提交表单
            form.submit();
        }

        // 在最外层定义全局变量和函数
        const speechSynthesis = window.speechSynthesis;

        // 修改语音播报函数
        let playQueue = [];  // 用于存储待播放的消息队列
        let isPlaying = false;  // 标记是否正在播放

        // 语音播报函数
        function speakAlarm(message) {
            if (!voiceAlertSwitch.checked || !message || !window.speechSynthesis) {
                return;
            }

            try {
                // 将消息添加到队列
                if (!playQueue.includes(message)) {  // 避免重复添加相同消息
                    playQueue.push(message);
                }

                // 如果没有正在播放，则开始播放
                if (!isPlaying) {
                    playNext();
                }
            } catch (error) {
                console.error('语音播报异常:', error);
                isPlaying = false;
            }
        }

        // 播放队列中的下一条消息
        function playNext() {
            if (playQueue.length === 0 || !voiceAlertSwitch.checked) {
                isPlaying = false;
                return;
            }

            try {
                isPlaying = true;
                const message = playQueue[0];  // 获取队列中的第一条消息

                // 取消当前正在播放的语音
                speechSynthesis.cancel();

                const settings = JSON.parse(localStorage.getItem('voiceSettings') || '{}');
                const utterance = new SpeechSynthesisUtterance(message);

                utterance.lang = 'zh-CN';
                utterance.volume = settings.volume || 1;
                utterance.rate = settings.rate || 1;
                utterance.pitch = settings.pitch || 1;

                // 播放结束回调
                utterance.onend = function () {
                    playQueue.shift();  // 移除已播放的消息
                    // 延迟一段时间后播放下一条
                    setTimeout(() => {
                        playNext();
                    }, 500);  // 500ms 的间隔
                };

                // 错误处理
                utterance.onerror = function (event) {
                    console.error('语音播报错误:', event);
                    playQueue.shift();  // 移除出错的消息
                    isPlaying = false;
                    // 延迟后尝试继续播放
                    setTimeout(() => {
                        playNext();
                    }, 1000);  // 错误后等待1秒再尝试
                };

                speechSynthesis.speak(utterance);

            } catch (error) {
                console.error('播放过程出错:', error);
                playQueue.shift();  // 移除出错的消息
                isPlaying = false;
                // 延迟后尝试继续播放
                setTimeout(() => {
                    playNext();
                }, 1000);
            }
        }

        // 保存语音设置
        function saveVoiceSettings() {
            const settings = {
                volume: document.getElementById('voiceVolume').value,
                rate: document.getElementById('voiceRate').value,
                pitch: document.getElementById('voicePitch').value,
                repeat: document.getElementById('voiceRepeat').checked
            };
            localStorage.setItem('voiceSettings', JSON.stringify(settings));
            updateSettingValues();
        }

        // 更新设置值显示
        function updateSettingValues() {
            document.getElementById('volumeValue').textContent = Math.round(document.getElementById('voiceVolume').value * 100);
            document.getElementById('rateValue').textContent = Math.round(document.getElementById('voiceRate').value * 100);
            document.getElementById('pitchValue').textContent = Math.round(document.getElementById('voicePitch').value * 100);
        }

        // 测试语音设置
        function testVoiceSettings() {
            // 清空当前队列
            playQueue = [];
            isPlaying = false;
            speechSynthesis.cancel();

            const testMessage = "这是一条测试语音，用于调试语音播报效果。";
            speakAlarm(testMessage);
        }

        // 加载语音设置
        function loadVoiceSettings() {
            const settings = JSON.parse(localStorage.getItem('voiceSettings') || '{}');
            document.getElementById('voiceVolume').value = settings.volume || 1;
            document.getElementById('voiceRate').value = settings.rate || 1;
            document.getElementById('voicePitch').value = settings.pitch || 1;
            document.getElementById('voiceRepeat').checked = settings.repeat !== false;
            updateSettingValues();
        }

        document.addEventListener('DOMContentLoaded', function () {
            // 建立WebSocket连接
            const ws = new WebSocket(
                'ws://' + window.location.host + '/ws/subscriptions/'
            );

            // 更新状态显示
            function updateStatus(element, status, message = '') {
                const statusBadge = element.querySelector('.status');
                statusBadge.className = 'badge status';

                switch (status) {
                    case 'connected':
                        statusBadge.classList.add('bg-success');
                        statusBadge.textContent = '已连接';
                        break;
                    case 'error':
                        statusBadge.classList.add('bg-danger');
                        statusBadge.textContent = message || '错误';
                        break;
                    case 'alarm':
                        statusBadge.classList.add('bg-danger');
                        statusBadge.textContent = '报警';
                        break;
                    case 'normal':
                        statusBadge.classList.add('bg-success');
                        statusBadge.textContent = '正常';
                        break;
                    default:
                        statusBadge.classList.add('bg-secondary');
                        statusBadge.textContent = '未连接';
                }
            }

            // 更新数据显示
            function updateValue(element, value, timestamp) {
                const valueElement = element.querySelector('.value');
                const timestampElement = element.querySelector('.timestamp');

                if (valueElement) {
                    valueElement.textContent = typeof value === 'number' ? value.toFixed(2) : value;
                }

                if (timestampElement && timestamp) {
                    // 处理时间戳
                    let date;
                    if (typeof timestamp === 'string') {
                        // 如果是ISO格式的字符串
                        date = new Date(timestamp);
                    } else if (typeof timestamp === 'number') {
                        // 如果是毫秒时间戳
                        date = new Date(timestamp);
                    } else {
                        date = new Date();
                    }
                    timestampElement.textContent = date.toLocaleString('zh-CN');
                }
            }

            // 显示报警提示
            function showAlarmToast(message, type = 'mqtt') {
                const toast = document.createElement('div');
                toast.className = 'toast position-fixed bottom-0 end-0 m-3';
                toast.setAttribute('role', 'alert');
                toast.setAttribute('aria-live', 'assertive');
                toast.setAttribute('aria-atomic', 'true');

                toast.innerHTML = `
            <div class="toast-header bg-danger text-white">
                <i class="bi bi-exclamation-triangle me-2"></i>
                <strong class="me-auto">报警提醒 - ${type === 'mqtt' ? 'MQTT' : 'OPC UA'}</strong>
                <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
            </div>
            <div class="toast-body">
                ${message}
            </div>
        `;

                document.body.appendChild(toast);
                const bsToast = new bootstrap.Toast(toast);
                bsToast.show();

                // 5秒后自动关闭并移除
                setTimeout(() => {
                    bsToast.hide();
                    setTimeout(() => toast.remove(), 500);
                }, 5000);
            }

            // 处理WebSocket消息
            ws.onmessage = function (event) {
                const data = JSON.parse(event.data);
                console.log('Received message:', data);  // 添加调试日志

                let element;
                if (data.type === 'subscription_data') {
                    const messageData = data.data;
                    switch (messageData.type) {
                        case 'status_update':
                            if (messageData.subscription_type === 'opcua') {
                                element = document.getElementById(`opcua-${messageData.subscription_id}`);
                                if (element) {
                                    updateStatus(element, messageData.status, messageData.message);
                                }
                            } else if (messageData.subscription_type === 'mqtt') {
                                element = document.querySelector(`tr#mqtt-item-${messageData.item_id}[data-values-id]`);
                                if (element) {
                                    updateStatus(element, messageData.status, messageData.message);
                                }
                            }
                            break;

                        case 'data_update':
                            if (messageData.subscription_type === 'opcua') {
                                element = document.getElementById(`opcua-${messageData.subscription_id}`);
                                if (element) {
                                    updateValue(element, messageData.value, messageData.timestamp);
                                    updateStatus(element, 'normal');
                                }
                            } else if (messageData.subscription_type === 'mqtt') {
                                element = document.querySelector(`tr#mqtt-item-${messageData.item_id}[data-values-id]`);
                                if (element) {
                                    updateValue(element, messageData.value, messageData.timestamp);
                                    updateStatus(element, 'normal');
                                }
                            }
                            break;

                        case 'alarm_update':
                            if (messageData.subscription_type === 'opcua') {
                                element = document.getElementById(`opcua-${messageData.subscription_id}`);
                                if (element) {
                                    updateStatus(element, 'alarm');
                                    updateValue(element, messageData.value, messageData.timestamp);
                                    speakAlarm(messageData.message);
                                    showAlarmToast(messageData.message, 'opcua');
                                }
                            } else if (messageData.subscription_type === 'mqtt') {
                                element = document.querySelector(`tr#mqtt-item-${messageData.item_id}[data-values-id]`);
                                if (element) {
                                    updateStatus(element, 'alarm');
                                    updateValue(element, messageData.value, messageData.timestamp);
                                    speakAlarm(messageData.message);
                                    showAlarmToast(messageData.message, 'mqtt');
                                }
                            }
                            break;
                    }
                }
            };

            // WebSocket错误处理
            ws.onerror = function (error) {
                console.error('WebSocket error:', error);
            };

            // WebSocket关闭处理
            ws.onclose = function (event) {
                console.log('WebSocket closed:', event);
                // 更新所有状态为未连接
                document.querySelectorAll('.status').forEach(element => {
                    element.className = 'badge bg-secondary status';
                    element.textContent = '未连接';
                });
            };

            // 在页面加载完成后，为分页链接添加当前的搜索参数
            const searchParams = new URLSearchParams(window.location.search);
            searchParams.delete('page'); // 删除page参数，因为分页链接已经包含了

            if (searchParams.toString()) {
                const paginationLinks = document.querySelectorAll('.pagination .page-link');
                paginationLinks.forEach(link => {
                    if (link.href.includes('?')) {
                        link.href += '&' + searchParams.toString();
                    } else {
                        link.href += '?' + searchParams.toString();
                    }
                });
            }


            // 加载语音设置
            loadVoiceSettings();

            // 绑定设置变更事件
            document.querySelectorAll('#voiceSettingsModal input').forEach(input => {
                input.addEventListener('change', saveVoiceSettings);
                if (input.type === 'range') {
                    input.addEventListener('input', updateSettingValues);
                }
            });

            // 检查浏览器是否支持语音合成
            if (!window.speechSynthesis) {
                console.warn('浏览器不支持语音合成');
                const voiceSwitch = document.getElementById('voiceAlertSwitch');
                const voiceSettingsBtn = document.querySelector('[data-bs-target="#voiceSettingsModal"]');
                if (voiceSwitch) {
                    voiceSwitch.disabled = true;
                    voiceSwitch.checked = false;
                }
                if (voiceSettingsBtn) {
                    voiceSettingsBtn.disabled = true;
                }
                return;
            }

            // 绑定语音开关事件
            // 修改语音开关事件处理
            const voiceAlertSwitch = document.getElementById('voiceAlertSwitch');
            voiceAlertSwitch.addEventListener('change', function () {
                localStorage.setItem('voiceAlertEnabled', this.checked);
                if (!this.checked) {
                    // 停止所有播放
                    playQueue = [];
                    isPlaying = false;
                    speechSynthesis.cancel();
                }
            });

            // 恢复语音开关状态
            const enabled = localStorage.getItem('voiceAlertEnabled');
            if (enabled !== null) {
                voiceAlertSwitch.checked = enabled === 'true';
            }
        });

    </script>
{% endblock %} 